﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using Newtonsoft.Json;
using System.Text;
using TCL.EO;
using System.Web.Script.Serialization;
using System.IO;
using System.Xml.Serialization;

namespace TCL.FUNC
{
    public class ConvertEx
    {
        public class SQLite
        {
            public static String DateTime2String(DateTime tInput)
            {
                return tInput.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }

            public static String Boolean2Number(Boolean bInput)
            {
                return bInput ? "1" : "0";
            }

            public static String RemoveSpecialCharacter(String sInput)
            {
                return StringEx.Trim(sInput).Replace("'", "''");
            }
        }


        public static DateTime StringFB2DateTime(String sInput, String sFormat)
        {
            DateTime tRet = new DateTime();
            try
            {
                DateTime.TryParseExact(sInput, sFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out tRet);
            }
            catch { }
            return tRet;
        }

        public static DataTable ConvertListObjectToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dt = new DataTable();
            for (int i = 0; i <= properties.Count - 1; i++)
            {
                PropertyDescriptor property = properties[i];
                dt.Columns.Add(property.Name, property.PropertyType);
            }
            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i <= values.Length - 1; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }
                dt.Rows.Add(values);
            }
            return dt;
        }

        public static List<T> ConvertRowsToList<T>(DataTable input, Converter<DataRow, T> conversion)
        {
            List<T> retval = new List<T>();
            foreach (DataRow dr in input.Rows)
                retval.Add(conversion(dr));
            return retval;
        }

        public static String BytesToString(long byteCount)
        {
            string[] suf = { " (B)", " (KB)", " (MB)", " (GB)", " (TB)", " (PB)", " (EB)" };
            if (byteCount == 0)
                return "0" + suf[0];
            long bytes = Math.Abs(byteCount);
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return (Math.Sign(byteCount) * num).ToString() + suf[place];
        }

        public static Int32 Convert_ToInt32_ReturnDefault(object strSrc, Int32 iResult)
        {
            Int32.TryParse(Convert.ToString(strSrc), out iResult);
            return iResult;
        }

        public static Int16 Convert_ToInt16_ReturnDefault(object strSrc, Int16 iResult)
        {
            Int16.TryParse(Convert.ToString(strSrc), out iResult);
            return iResult;
        }

        public static string ToBase64(string src, Encoding encoding)
        {
            byte[] b = encoding.GetBytes(src);
            return Convert.ToBase64String(b);
        }

        public static string Base64ToString(string src, Encoding encoding)
        {
            byte[] b = Convert.FromBase64String(src);
            return encoding.GetString(b);
        }

        public static string StringToHex(string str)
        {
            var sb = new StringBuilder();
            var bytes = Encoding.Unicode.GetBytes(str);
            foreach (var t in bytes)
            {
                sb.Append(t.ToString("X2"));
            }
            return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
        }

        public static string HexToString(string hexString)
        {
            var bytes = new byte[hexString.Length / 2];
            for (var i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
        }


        public static Boolean Convert_iStatus_bStatus(Int16 iStatus)
        {
            switch (iStatus)
            {
                case 1:
                case 2: return true;
                case 3: return false;
                default:
                    return true;
            }
        }

        public static Int16 Convert_bStatus_iStatus(Boolean bStatus)
        {
            if (bStatus)
                return 1;
            else
                return 3;
        }

        public static List<KeyValueEO> Convert_ArrayString_KeyValueEO(String[] arrKey, String[] arrValue)
        {
            List<KeyValueEO> lstRet = new List<KeyValueEO>();
            if (arrKey != null && arrKey.Length > 0 && arrValue != null && arrValue.Length > 0 && arrKey.Length == arrValue.Length)
            {
                for (int i = 0; i < arrKey.Length; i++)
                {
                    lstRet.Add(new KeyValueEO(StringEx.Trim(arrKey[i]).Replace("\"", "'"), StringEx.Trim(arrValue[i]).Replace("\"", "'")));
                }
            }
            return lstRet;
        }

        public static String[] Convert_KeyValueEO_ArrayString(List<KeyValueEO> lstInput, Boolean isKey)
        {
            String[] arrRet = null;
            if (lstInput != null && lstInput.Count > 0)
            {
                arrRet = new String[lstInput.Count];
                for (int i = 0; i < lstInput.Count; i++)
                {
                    if (isKey)
                        arrRet[i] = lstInput[i].K;
                    else
                        arrRet[i] = lstInput[i].V;
                }
            }
            return arrRet;
        }

        public static String Convert_KeyValueEO_StringOfArray(List<KeyValueEO> lstInput, Boolean isKey, Boolean isRetBase64)
        {
            String strRet = null;
            if (lstInput != null && lstInput.Count > 0)
            {
                String[] arrRet = new String[lstInput.Count];
                for (int i = 0; i < lstInput.Count; i++)
                {
                    if (isKey)
                        arrRet[i] = lstInput[i].K;
                    else
                        arrRet[i] = lstInput[i].V;
                }
                JavaScriptSerializer jss = new JavaScriptSerializer();
                strRet = jss.Serialize(arrRet);
                strRet = ToBase64(strRet, System.Text.Encoding.UTF8);
            }
            return strRet;
        }



        public class JsonEx
        {
            public static IList<T> Json_2_ListObject<T>(String sInput, Type tType)
            {
                if (String.IsNullOrEmpty(sInput))
                    return null;
                else
                    return (IList<T>)JsonConvert.DeserializeObject(sInput, tType);
            }

            public static String ListObject_2_Json<T>(List<T> lstInput) where T : class
            {
                return JsonConvert.SerializeObject(lstInput);
            }

            public static T Json_2_Object<T>(String sInput, Type tType)
            {
                if (String.IsNullOrEmpty(sInput))
                    return default(T);
                else
                    return (T)JsonConvert.DeserializeObject(sInput, tType);
            }

            public static String Object_2_Json(Object objInput)
            {
                return JsonConvert.SerializeObject(objInput);
            }
        }

        public class DataTableEx
        {
            public static T DataTable_2_Object<T>(DataTable dtInput, Type tType)
            {
                if (CheckEx.IsDataTable(dtInput))
                    return (T)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(dtInput), tType);
                else
                    return default(T);
            }

            public static IList<T> DataTable_2_ListObject<T>(DataTable dtInput, Type tType)
            {
                if (CheckEx.IsDataTable(dtInput))
                    return (IList<T>)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(dtInput), tType);
                else
                    return null;
            }
        }

        public class XmlEx
        {
            public static Object Xml_2_ListObject(String sInput, System.Type type = null)
            {
                System.Xml.Serialization.XmlSerializer ser = default(System.Xml.Serialization.XmlSerializer);
                ser = new System.Xml.Serialization.XmlSerializer(type);
                System.IO.StringReader stream = new System.IO.StringReader(sInput);
                System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(stream);
                Object a = ser.Deserialize(reader);
                return a;
            }

            public static String ListObject_2_Xml<T>(List<T> objInput, String sFileName) where T : class
            {
                if (!String.IsNullOrEmpty(sFileName))
                {
                    StreamWriter objStreamWriter = new StreamWriter(sFileName);
                    XmlSerializer x = new XmlSerializer(objInput.GetType());
                    x.Serialize(objStreamWriter, objInput);
                    objStreamWriter.Close();
                }
                XmlSerializer serializer = new XmlSerializer(objInput.GetType());
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, objInput);
                writer.ToString();
                return writer.ToString();
            }

            public static String Object_2_Xml<T>(T objInput, String sFileName) where T : class
            {
                if (!String.IsNullOrEmpty(sFileName))
                {
                    StreamWriter objStreamWriter = new StreamWriter(sFileName);
                    XmlSerializer x = new XmlSerializer(objInput.GetType());
                    x.Serialize(objStreamWriter, objInput);
                    objStreamWriter.Close();
                }
                XmlSerializer serializer = new XmlSerializer(objInput.GetType());
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, objInput);
                writer.ToString();
                return writer.ToString();
            }

            public static String ReplaceSpecialXMLCharater(String sInput)
            {
                sInput = sInput.Replace("&", "&amp;");
                sInput = sInput.Replace("<", "&lt;");
                sInput = sInput.Replace(">", "&gt;");
                sInput = sInput.Replace("\"", "&quot;");
                sInput = sInput.Replace("''", "&apos;");
                return sInput;
            }

            public static String RollbackSpecialXMLCharater(String sInput)
            {
                sInput = sInput.Replace("&amp;", "&");
                sInput = sInput.Replace("&lt;", "<");
                sInput = sInput.Replace("&gt;", ">");
                sInput = sInput.Replace("&quot;", "\"");
                sInput = sInput.Replace("&apos;", "''");
                return sInput;
            }
        }
    }
}
